﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using 简单三层架构.DBUtility;
using 简单三层架构.IDAL;
using 简单三层架构.Model;

namespace 简单三层架构.DAL
{
    public class Order : IOrder
    {
        private const string SQL_INSERT_ORDER = "INSERT INTO Orders(";
        private const string SQL_SELECT_ORDER = "SELECT * FROM Orders";
        private const string SQL_INSERT_LINEITEM = "INSERT INTO LineItems VALUES(";

        private const string PARM_USER_ID = "UserId";
        private const string PARM_ORDER_TIME = "OrderTime";
        private const string PARM_ADDRESS = "Address";
        private const string PARM_LINE_NUMBER = "LineNumber";
        private const string PARM_ITEM_ID = "ItemId";
        private const string PARM_QUANTITY = "Quantity";
        private const string PARM_UNIT_PRICE = "UnitPrice";


        public void Insert(OrderInfo order)
        {
            using (SqlConnection connection = SqlHelper.GetConnection())
            {
                StringBuilder builder = new StringBuilder();
                builder.Append(SQL_INSERT_ORDER);
                builder.Append(PARM_USER_ID + "," + PARM_ORDER_TIME + "," + PARM_ADDRESS);
                builder.Append(") VALUES (");
                builder.Append(string.Format("'{0}','{1}','{2}'", order.UserId, DateTime.Now.ToString(), order.Address));
                builder.Append(")");

                SqlHelper.ExecuteNonQuerySqlCommand(builder.ToString(),
                                                    connection);

                for (int i = 0; i < order.LineItems.Count(); i++)
                {
                    builder = new StringBuilder();
                    LineItemInfo currentLineItem = order.LineItems[i];

                    builder.Append(SQL_INSERT_LINEITEM).Append(order.OrderId).Append(",").Append(i.ToString()).Append(
                        ",").Append(",").Append(currentLineItem.Quantity).Append(",").Append(currentLineItem.UnitPrice);
                    SqlHelper.ExecuteNonQuerySqlCommand(builder.ToString(), connection);
                }
            }
        }

        public List<OrderInfo> GetAllOrders()
        {
            List<OrderInfo> orders = new List<OrderInfo>();

            return orders;
        }

        public OrderInfo GetOrderById(int orderId)
        {
            OrderInfo order = new OrderInfo();

            return order;
        }
    }
}